package com.inmerweb.app.impl;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

import com.inmerweb.app.domain.UserEntity;
import com.inmerwebapp.services.UserAuthenticationProviderService;

/**
 * 
 * Clase que implementa el interface para gestionar autenticacion del usuario
 * 
 * @author Daniel Pascual Sanchez
 *
 */
public class UserAuthenticationProviderServiceImpl implements
		UserAuthenticationProviderService {

	private AuthenticationManager authenticationManager;

	/**
	 * Gestionar autenticacion del usuario
	 * 
	 * @param user
	 *            , processType
	 * @return
	 */
	public boolean processUserAuthentication(UserEntity user, String processType) {

		try {

			if (processType.equals("login")) {
				// Hash de la clave en md5
				PasswordEncoder crypto = new Md5PasswordEncoder();
				user.setPassword(crypto.encodePassword(user.getPassword(), null));
			}
			Authentication request = new UsernamePasswordAuthenticationToken(
					user.getUserName(), user.getPassword());
			// Llama a userDetailsService para comprobar los datos de ese
			// usuario en BD
			Authentication result = authenticationManager.authenticate(request);

			SecurityContextHolder.getContext().setAuthentication(result);

			return true;
		} catch (AuthenticationException e) {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, e
							.getMessage(), ""));
			return false;
		}

	}

	public AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(
			AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

}
